score_agree_high <- function(.response) {
  out <- case_when(
    .response == "Disagree" ~ 1,
    .response == "More or Less Disagree" ~ 2,
    .response == "Neither Agree nor Disagree" ~ 3,
    .response == "More or Less Agree" ~ 4,
    .response == "Agree" ~ 5
  )
  return(out)
}


score_agree_low <- function(.response) {
  out <- case_when(
    .response == "Disagree" ~ 5,
    .response == "More or Less Disagree" ~ 4,
    .response == "Neither Agree nor Disagree" ~ 3,
    .response == "More or Less Agree" ~ 2,
    .response == "Agree" ~ 1
  )
}

make_terciles <- function(.variable) {
  out <- cut(.variable,
    quantile(.variable, c(0:3 / 3)),
    include.lowest = TRUE,
    labels = c("Low", "Medium", "High")
  )
}

expand_profile_data <- function(.data1, .data2) {
  .data1 %>%
    left_join(.data2 %>% select(ResponseId, Q5.1:Q9.6, Q29.1, Q30.1:Q35.1),
      by = join_by(ResponseId)
    ) %>%
    mutate(
      nationalism_score = (score_agree_high(Q5.1) +
        score_agree_high(Q6.1) +
        score_agree_high(Q7.1)) / 3,
      discrimination_score = score_agree_high(Q29.1),
      resentment_score = (score_agree_high(Q30.1) +
        score_agree_high(Q31.1) +
        score_agree_low(Q32.1) +
        score_agree_high(Q33.1) +
        score_agree_low(Q34.1) +
        score_agree_high(Q35.1)) / 6
    ) %>%
    mutate(
      nationalism_tercile = make_terciles(nationalism_score),
      resentment_tercile = make_terciles(resentment_score),
      discrimination_tercile = case_when(
        discrimination_score %in% 1:2 ~ "Low",
        discrimination_score == 3 ~ "Medium",
        discrimination_score %in% 4:5 ~ "High"
      ),
      discrimination_tercile = factor(discrimination_tercile,
        levels = c("Low", "Medium", "High")
      ),
      political_affiliation = case_when(
        str_detect(Q8.3, "[Ll]eft") ~ "Left",
        Q8.3 == "Middle of the road" ~ "Middle of the Road",
        str_detect(Q8.3, "[Rr]ight") ~ "Right"
      ),
      political_affiliation = factor(political_affiliation,
        levels = c("Left", "Middle of the Road", "Right")
      ),
      age_range = make_terciles(Q9.2),
      age_range = case_when(
        age_range == "Low" ~ "18 to 43",
        age_range == "Medium" ~ "44 to 65",
        age_range == "High" ~ "66+"
      ),
      college_grad = case_when(
        Q9.5 == "Universities and Graduate Schools" ~ "College/University Graduate",
        TRUE ~ "Not a College/University Graduate"
      ),
      college_grad = factor(college_grad, levels = c("College/University Graduate", "Not a College/University Graduate"))
    )
}
